import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PopoverController } from '@ionic/angular';

import { HttpService } from '../service/http.service';
import { MessageService } from '../service/message.service';
import { ChatsItemPopoverComponent, OperationType } from './chats-item-popover/chats-item-popover.component';

@Component({
  selector: 'app-chats',
  templateUrl: './chats.page.html',
  styleUrls: ['./chats.page.scss'],
})
export class ChatsPage implements OnInit {

  messages: any;

  unread = 0;

  constructor(private router: Router, private popoverController: PopoverController, private httpService: HttpService, private messageService: MessageService) { }

  async ngOnInit() {
    await this.getMessage()
  }

  async getMessage() {
    const { data } = await this.httpService.getMessages()
    this.messages = data
    this.unread = 0
    for (const friend of this.messages) {
      if (!friend.nohup) {
        this.unread += friend.unread
      }
    }
    this.messageService.setMessageCount(this.unread)
  }

  itemTapped(item) {
    this.router.navigate(['/chat'], { queryParams: { id: item.id, name: item.name } })
  }

  async itemPressed(event, item) {
    const popover = await this.popoverController.create({
      component: ChatsItemPopoverComponent,
      event: event,
      showBackdrop: false
    })
    await popover.present()
    item.active = true

    const { data } = await popover.onDidDismiss()
    this.itemHandle(item, data)
    item.active = false
  }

  itemHandle(record: any, type: OperationType) {
    switch (type) {
      case OperationType.Unread:
        console.log(record, '标为未读')
        break;

      case OperationType.Top:
        console.log(record, '置顶该聊天')
        break;

      case OperationType.Hide:
        console.log(record, '不再显示该聊天')
        break;

      case OperationType.Delete:
        console.log(record, '删除该聊天')
        break;
    }
  }
}
